// 封装购物车模块
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useUserStore } from "./userStore";
import { insertCartAPI, findNewCartListAPI, delCartAPI } from "@/apis/cart";
export const useCartStore = defineStore(
  "cart",
  () => {
    const userStore = useUserStore();
    const isLogin = computed(() => userStore.userInfo.token);
    // 1定义state-cartList
    const cartList = ref([]);
    // 获取最新购物车列表
    const getNewCartList = async () => {
      const res = await findNewCartListAPI();
      cartList.value = res.result;
    };
    // 2.定义action
    const addCart = async (goods) => {
      const { skuId, count } = goods;
      if (isLogin.value) {
        // 登录之后的逻辑
        await insertCartAPI({ skuId, count });
        getNewCartList();
      } else {
        // 添加购物车操作
        const findResult = cartList.value.find((x) => x.skuId === goods.skuId);
        if (findResult) {
          findResult.count++;
        } else {
          cartList.value.push(goods);
        }
        // 已添加过 -count +1
        // 没有添加过 -直接push
      }
    };
    // 删除商品
    const delCart = async (skuId) => {
      if (isLogin.value) {
        // 调用接口实现购物车的删除功能
        await delCartAPI([skuId]);
        getNewCartList();
      } else {
        // 思路：
        // 1.找到要删除的下标值 splice
        // 2.使用数组的过滤方法 filter
        cartList.value = cartList.value.filter((x) => x.skuId !== skuId);
      }
    };
    // 清除购物车
    const clearCart = () => {
      cartList.value = [];
    };
    // 单选功能
    const singleCheck = (skuId, selected) => {
      // 通过skuId知道更改的是谁的状态，将状态赋值给这个对象
      const findResult = cartList.value.find((x) => x.skuId === skuId);
      findResult.selected = selected;
    };
    // 全选或全不选
    const allCheck = (selected) => {
      cartList.value.forEach((x) => {
        x.selected = selected;
      });
    };
    // 总数量
    const allCount = computed(() =>
      cartList.value.reduce((sum, item) => sum + item.count, 0)
    );
    // 总的价格
    const allPrice = computed(() => {
      return cartList.value.reduce(
        (sum, item) => sum + item.price * item.count,
        0
      );
    });
    // 是否全选
    const isAll = computed(() => {
      return cartList.value.every((x) => x.selected);
    });
    // 已选数量
    const selectedCount = computed(() =>
      cartList.value
        .filter((x) => x.selected)
        .reduce((sum, item) => sum + item.count, 0)
    );
    // 已选商品总价
    const selectedPrice = computed(() =>
      cartList.value
        .filter((x) => x.selected)
        .reduce((sum, item) => sum + item.count * item.price, 0)
    );

    return {
      cartList,
      addCart,
      delCart,
      allCount,
      allPrice,
      singleCheck,
      isAll,
      allCheck,
      selectedCount,
      selectedPrice,
      clearCart,
      getNewCartList,
    };
  },
  { persist: true }
);
